package com.naihe.anderson.sms.manager;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;

import com.naihe.anderson.sms.R;
import com.naihe.anderson.sms.activity.NoteActivity;
import com.naihe.anderson.sms.application.NhSmsApp;
import com.naihe.anderson.sms.constants.NhSmsConstants;
import com.naihe.anderson.sms.dao.RecordMoneyDao;
import com.naihe.anderson.sms.entity.CapitalInfo;
import com.naihe.anderson.sms.entity.Nhsms;
import com.naihe.anderson.sms.entity.NhsmsSession;
import com.naihe.anderson.sms.entity.Note;
import com.naihe.anderson.sms.entity.RecordMoney;
import com.naihe.anderson.sms.listener.OnCapitalListener;
import com.naihe.anderson.sms.listener.OnRecordListener;
import com.naihe.anderson.sms.util.FileUtil;
import com.naihe.anderson.sms.util.ObjectUtil;
import com.naihe.anderson.sms.xml.ExpenditureXmlUtil;
import com.naihe.anderson.sms.xml.IncomeXmlUtil;

public class RecordMoneyMgr {
	
	NhSmsApp application;
	RecordMoneyDao recordMoneyDao;
	Map<String, String> bankPhone;
	
	OnRecordListener onRecordListener;//账本列表明细监听
	OnRecordListener onMoneyListener;//账本主页监听
	OnCapitalListener capitalListener;//资金银行变动记录
	
	private float today_income = 0;
	private float today_expenditure = 0;
	private float month_income = 0;
	private float month_expenditure = 0;
	
	//在内存中只留 本月的数据
	List<CapitalInfo> capitalInfoList = new ArrayList<CapitalInfo>();
	List<RecordMoney> recordMoneyList = new ArrayList<RecordMoney>();
	List<String> expenditure = new ArrayList<String>();
	List<String> income = new ArrayList<String>();
	
	public RecordMoneyMgr(NhSmsApp app){
		this.application = app;
		recordMoneyDao = new RecordMoneyDao(app);
	}
	
	public void initRecordMoney(){
		new InitRecordMoneyDbTask().execute();
		new InitCapotalDbTask().execute();
	}
	
	public void calculateRecordMoney(){
		jisuan();
	}
	
	public void searchRecordMoney(long beginTime, long endTime, Handler handler, Message message){
		new SearchRecordMoneyDbTask(beginTime, endTime, handler, message).execute();
	}
	
	public void insertRecordMoney(RecordMoney insertmoney){
		recordMoneyList.add(insertmoney);
		jisuan();
		new InsertRecordMoneyDbTask(insertmoney).execute();
		if(onRecordListener != null) onRecordListener.onDataChanged();
	}
	
	/**
	 * 农业银行 95599
	 * 招商银行 95555 
	 * 中国银行 95566         
	 * 工商银行 95588 
	 * 交通银行 95559
	 * 建设银行 95533 
	 */
	public String getPhoneBank(String phone){
		if(ObjectUtil.phoneNumberIsMobile(phone))
			return "个人";
		
		if(bankPhone == null){
			bankPhone = new HashMap<String, String>();
			bankPhone.put("95599", "农业银行");
			bankPhone.put("95555", "招商银行");
			bankPhone.put("95566", "中国银行");
			bankPhone.put("95588", "工商银行");
			bankPhone.put("95559", "交通银行");
			bankPhone.put("95533", "建设银行");
		}
		
		String bank = bankPhone.get(phone);
		if(TextUtils.isEmpty(bank))
			bank = "银行";
		
		return bank;
	}
	
	public void deltetRecordMoney(RecordMoney delmoney){
		recordMoneyList.remove(delmoney);
		jisuan();
		new DeleteRecordMoneyDbTask(delmoney).execute();
		if(onRecordListener != null) onRecordListener.onDataChanged();
	}
	
	public void moneyToNote(RecordMoney noteMoney){
		new MoneyToNoteTask(noteMoney).execute();
	}
	
	public void removePic(RecordMoney noteMoney, String type){
		new RemovePicTask(noteMoney, type).execute();
	}
	
	private void jisuan(){
		today_income = 0;
		today_expenditure = 0;
		month_income = 0;
		month_expenditure = 0;
		Date date = new Date();
		for (RecordMoney recordMoney : recordMoneyList) {
			Date recordMoneyDate = new Date(recordMoney.createTime);
			//今天
			if(date.getYear()==recordMoneyDate.getYear() && date.getMonth()==recordMoneyDate.getMonth() && date.getDate()==recordMoneyDate.getDate()){
				if(recordMoney.actionType == RecordMoney.ACTION_TYPE_EXPENDITURE){
					today_expenditure += recordMoney.moneyNum;
				} else {
					today_income += recordMoney.moneyNum;
				}
			}
			
			//本月
			if(date.getYear()==recordMoneyDate.getYear() && date.getMonth()==recordMoneyDate.getMonth()){
				if(recordMoney.actionType == RecordMoney.ACTION_TYPE_EXPENDITURE){
					month_expenditure += recordMoney.moneyNum;
				} else {
					month_income += recordMoney.moneyNum;
				}
			}
		}
		
		if(onMoneyListener != null)
			onMoneyListener.onDataChanged();
	}
	
	//-------------------------------------------
	public void insertCapotal(CapitalInfo addInfo, boolean matchingOldSms){
		new InsertCapitalDbTask(addInfo, matchingOldSms).execute();
	}
	
	public void addCapotal(Nhsms nhsms){
		for(CapitalInfo capitalInfo : capitalInfoList){
			if(capitalInfo.number.equals(ObjectUtil.phoneNumberFormatPrefix(nhsms.getAddress()))){
				new AddCapitalDbTask(nhsms, capitalInfo).execute();
				break;
			}
		}
	}
	
	public void deleteCapotal(CapitalInfo addInfo, boolean matchingOldSms){
		new DeleteCapitalDbTask(addInfo, matchingOldSms).execute();
	}
	
	//=======================================================================================
	public void setOnRecordListener(OnRecordListener onRecordListener) {
		this.onRecordListener = onRecordListener;
	}
	public void setOnMoneyListener(OnRecordListener onRecordListener) {
		this.onMoneyListener = onRecordListener;
	}
	public void setOnCapitalListener(OnCapitalListener capitalListener) {
		this.capitalListener = capitalListener;
	}
	
	public List<RecordMoney> getRecordMoneyList(){
		return recordMoneyList;
	}
	
	public List<CapitalInfo> getCapitalInfoList(){
		return capitalInfoList;
	}
	
	public List<String> getExpenditure(){
		return expenditure;
	}
	
	public int getExpenditureSize(){
		return expenditure.size();
	}
	
	public List<String> getIncome(){
		return income;
	}
	
	public int getIncomeSize(){
		return income.size();
	}
	
	public float getToday_income() {
		return today_income;
	}

	public float getToday_expenditure() {
		return today_expenditure;
	}

	public float getMonth_income() {
		return month_income;
	}

	public float getMonth_expenditure() {
		return month_expenditure;
	}
	//=======================================================================================
	class SearchRecordMoneyDbTask extends AsyncTask<String, Object, Boolean>{
		
		List<RecordMoney> recordMoneyListsTemp = null;
		long beginTime = 0;
		long endTIme = 0;
		Handler mHandler;
		Message message;
		
		public SearchRecordMoneyDbTask(long l1, long l2, Handler handler, Message msg){
			recordMoneyListsTemp = new ArrayList<RecordMoney>();
			beginTime = l1;
			endTIme = l2;
			mHandler = handler;
			message = msg;
		}
		
		@Override
		protected void onPreExecute() {
		}
		
		@Override
		protected Boolean doInBackground(String... params) {
			if(beginTime == 0 || endTIme == 0){
				return false;
			}
			recordMoneyListsTemp.addAll(recordMoneyDao.queryAllRecordMoneyList(beginTime, endTIme));
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if(result != null && !result){
				recordMoneyListsTemp.addAll(recordMoneyList);
			}
			message.obj = recordMoneyListsTemp;
			mHandler.sendMessage(message);
		}
	}

	class RemovePicTask extends AsyncTask<String, Object, Boolean>{
		
		RecordMoney money = null;
		String type = null;
		
		public RemovePicTask(RecordMoney money, String type){
			this.money = money;
			this.type = type;
		}
		
		@Override
		protected void onPreExecute() {
			
		}
		
		@Override
		protected Boolean doInBackground(String... params) {
			if(type.equals(NhSmsConstants.MONRY_MAP_PREFIX)){
				if(!TextUtils.isEmpty(money.loation) && money.loation.indexOf("/") > 0){
					String mapName = money.loation.substring(0, money.loation.indexOf("/"));
					File mapFile = new File(FileUtil.getPicNotePath() + mapName);
					if(mapFile!= null && mapFile.exists()) mapFile.delete();
				}
				money.loation = "";
			} else {
				if(!TextUtils.isEmpty(money.projectPic)){
					File picFile = new File(FileUtil.getPicNotePath() + money.projectPic);
					if(picFile!= null && picFile.exists()) picFile.delete();
				}
				money.projectPic = "";
			}
			
			recordMoneyDao.insertOrUpdateRecordMoneyEntity(money);
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			FileUtil.addLog("RecordMoneyMgr::RemovePicTask finish", RecordMoneyMgr.class, "RecordMoneyMgr", null);
			Toast.makeText(application, R.string.record_pic_success, Toast.LENGTH_SHORT).show();
			for(RecordMoney money : recordMoneyList){
				if(money.rmid == money.rmid){
					if(type.equals(NhSmsConstants.MONRY_MAP_PREFIX)){
						money.loation = "";
					} else {
						money.projectPic = "";
					}
					break;
				}
			}
			
			if(onRecordListener != null) onRecordListener.onDataChanged();
		}
	}

	class InsertRecordMoneyDbTask extends AsyncTask<String, Object, Boolean>{
		
		List<RecordMoney> moneyList = new ArrayList<RecordMoney>();
		
		public InsertRecordMoneyDbTask(RecordMoney money){
			this.moneyList.add(money);
		}
		
		public InsertRecordMoneyDbTask(List<RecordMoney> moneyList){
			this.moneyList.addAll(moneyList);
		}
		
		@Override
		protected void onPreExecute() {
			
		}
		
		@Override
		protected Boolean doInBackground(String... params) {
			recordMoneyDao.insertOrUpdateRecordMoneyEntity(moneyList);
			for(RecordMoney money : moneyList){
				boolean ifCreate = true;
				if(money.actionType == RecordMoney.ACTION_TYPE_EXPENDITURE){
					for(String project : expenditure){
						if(project.equals(money.project)){
							ifCreate = false;
							break;
						}
					}
					if(ifCreate){
						expenditure.add(money.project);
					}
				} else {
					for(String project : income){
						if(project.equals(money.project)){
							ifCreate = false;
							break;
						}
					}
					if(ifCreate){
						income.add(money.project);
					}
				}
			}
			
			new ExpenditureXmlUtil().saveExpenditure(application, expenditure);
			new IncomeXmlUtil().saveExpenditure(application, income);
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			FileUtil.addLog("RecordMoneyMgr::InsertRecordMoneyDbTask finish", RecordMoneyMgr.class, "RecordMoneyMgr", null);
			Toast.makeText(application, R.string.record_success, Toast.LENGTH_SHORT).show();
			
		}
	}
	
	class DeleteRecordMoneyDbTask extends AsyncTask<String, Object, Boolean>{
		
		RecordMoney money = null;
		
		public DeleteRecordMoneyDbTask(RecordMoney money){
			this.money = money;
		}
		
		@Override
		protected void onPreExecute() {
			
		}
		
		@Override
		protected Boolean doInBackground(String... params) {
			recordMoneyDao.deleteRecordMoneyEntity(money);
			if(!TextUtils.isEmpty(money.projectPic)){
				File picFile = new File(FileUtil.getPicNotePath() + money.projectPic);
				if(picFile!= null && picFile.exists()) picFile.delete();
			}
			if(!TextUtils.isEmpty(money.loation) && money.loation.indexOf("/") > 0){
				String mapName = money.loation.substring(0, money.loation.indexOf("/"));
				File mapFile = new File(FileUtil.getPicNotePath() + mapName);
				if(mapFile!= null && mapFile.exists()) mapFile.delete();
			}
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			FileUtil.addLog("RecordMoneyMgr::DeleteRecordMoneyDbTask finish", RecordMoneyMgr.class, "RecordMoneyMgr", null);
			Toast.makeText(application, R.string.record_del_success, Toast.LENGTH_SHORT).show();
		}
	}
	
	class MoneyToNoteTask extends AsyncTask<String, Object, Boolean>{
		
		RecordMoney money = null;
		
		public MoneyToNoteTask(RecordMoney money){
			this.money = money;
		}
		
		@Override
		protected void onPreExecute() {
			
		}
		
		@Override
		protected Boolean doInBackground(String... params) {
			Note note = new Note();//"picnote_"
			note.body = "账单类型：" + (money.actionType==RecordMoney.ACTION_TYPE_EXPENDITURE ? "支出" : "收入") + "\r\n"
					+ "账单对象：" + money.objectMember + "\r\n"
					+ "账单项目：" + money.project + "\r\n"
					+ "账单金额：" + money.moneyNum;
			note.createTime = new Date().getTime();
			note.id = note.createTime;
			note.title = "账单记录" + new SimpleDateFormat("MM-dd-HH").format(new Date(money.createTime));
			
			if(!TextUtils.isEmpty(money.projectPic)){
				note.picpath = money.projectPic;
			} else {
				if(!TextUtils.isEmpty(money.loation) && money.loation.indexOf("/") > 0){
					String mapName = money.loation.substring(0, money.loation.indexOf("/"));
					note.picpath = mapName;
				}
			}
			
			application.getNoteMgr().insert(note);
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			FileUtil.addLog("RecordMoneyMgr::MoneyToNoteTask finish", RecordMoneyMgr.class, "RecordMoneyMgr", null);
			Intent intent = new Intent(application, NoteActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			application.startActivity(intent);
		}
	}

	class InitRecordMoneyDbTask extends AsyncTask<String, Object, Boolean>{
		
		List<RecordMoney> recordMoneyListsTemp = null;
		List<String> expenditureTemp = null;
		List<String> incomeTemp = null;
		
		public InitRecordMoneyDbTask(){
			recordMoneyListsTemp = new ArrayList<RecordMoney>();
			expenditureTemp = new ArrayList<String>();
			incomeTemp = new ArrayList<String>();
		}
		
		@Override
		protected void onPreExecute() {
		}
		
		@Override
		protected Boolean doInBackground(String... params) {
			Date date = new Date();
			int year = date.getYear();
			int month = date.getMonth();
			Date beginDate = new Date(year, month, 1);
			Date endDate = new Date(year, month+1, 1);
			recordMoneyListsTemp.addAll(recordMoneyDao.queryAllRecordMoneyList(beginDate.getTime(), endDate.getTime()));
			expenditureTemp.addAll(new ExpenditureXmlUtil().getExpenditureByXml(application));
			incomeTemp.addAll(new IncomeXmlUtil().getIncomeByXml(application));
			
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			FileUtil.addLog("RecordMoneyMgr::InitRecordMoneyDbTask finish", RecordMoneyMgr.class, "RecordMoneyMgr", null);
			
			recordMoneyList.addAll(recordMoneyListsTemp);
			expenditure.addAll(expenditureTemp);
			income.addAll(incomeTemp);
			
			recordMoneyListsTemp.clear();
			recordMoneyListsTemp = null;
			expenditureTemp.clear();
			expenditureTemp = null;
			incomeTemp.clear();
			incomeTemp = null;
			
			Collections.sort(recordMoneyList);
			if(onRecordListener != null) onRecordListener.onDataChanged();
			jisuan();
		}
	}
	
	//--------------------------------------------------
	class InitCapotalDbTask extends AsyncTask<String, Object, Boolean>{
		
		List<CapitalInfo> capitalInfoListsTemp = null;
		
		public InitCapotalDbTask(){
			capitalInfoListsTemp = new ArrayList<CapitalInfo>();
		}
		
		@Override
		protected void onPreExecute() {
		}
		
		@Override
		protected Boolean doInBackground(String... params) {
			Date date = new Date();
			int year = date.getYear();
			int month = date.getMonth();
			Date beginDate = new Date(year, month, 1);
			Date endDate = new Date(year, month+1, 1);
			capitalInfoListsTemp.addAll(recordMoneyDao.queryAllCapitalInfoList(beginDate.getTime(), endDate.getTime()));
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			FileUtil.addLog("RecordMoneyMgr::InitCapotalDbTask finish", RecordMoneyMgr.class, "RecordMoneyMgr", null);
			
			capitalInfoList.addAll(capitalInfoListsTemp);
			
			capitalInfoListsTemp.clear();
			capitalInfoListsTemp = null;
			
			Collections.sort(capitalInfoList);
			if(capitalListener != null) capitalListener.onDataChanged();
		}
	}
	
	class AddCapitalDbTask extends AsyncTask<String, Object, Boolean>{
		
		List<RecordMoney> addRecordMoneyList = new ArrayList<RecordMoney>();
		CapitalInfo capitalInfo = null;
		Nhsms nhsms = null;
		
		public AddCapitalDbTask(Nhsms nhsms, CapitalInfo capitalInfo){
			this.capitalInfo = capitalInfo;
			this.nhsms = nhsms;
		}
		
		@Override
		protected void onPreExecute() {
		}
		
		@Override
		protected Boolean doInBackground(String... params) {
			try {
				String expenditureKeys = capitalInfo.expenditureKeys;
				String incomeKeys = capitalInfo.incomeIeys;
				
				String[] expenditureKeyArray = null;
				String[] incomeIeyArray = null;
				if(!TextUtils.isEmpty(expenditureKeys))
					expenditureKeyArray = expenditureKeys.split(";");
				if(!TextUtils.isEmpty(incomeKeys))
					incomeIeyArray = incomeKeys.split(";");
				
				long date = new Date().getTime();
				if(expenditureKeyArray != null)
				for(String expenditureKey : expenditureKeyArray){
					if(TextUtils.isEmpty(expenditureKey)) continue;
					
					String [] keyArray = expenditureKey.split("\\*");
					if(keyArray.length != 2) continue;
					
					Pattern p = Pattern.compile("^\\S*" + keyArray[0] + "(\\d*(,\\d{3})*\\.?\\d{0,3}(,\\d{1,3})*)" + keyArray[1] + "\\S*$");
					Matcher m = p.matcher(nhsms.getBody());
					if (m.matches()) {
						String number = m.group(1).trim().replace(",", "");
						RecordMoney recordMoney = new RecordMoney();
						recordMoney.rmid = date++;
						recordMoney.actionType = RecordMoney.ACTION_TYPE_EXPENDITURE;
						recordMoney.createTime = nhsms.getDate();
						recordMoney.moneyNum = Float.parseFloat(number);
						recordMoney.objectMember = capitalInfo.number;
						recordMoney.project = "银行/个人资金流动记录";
						recordMoney.remarks = nhsms.getBody() + "\r\n事件号码：" + nhsms.getAddress();
						addRecordMoneyList.add(recordMoney);
					}
				}
					
				if(incomeIeyArray != null)
				for(String incomeIey : incomeIeyArray){
					if(TextUtils.isEmpty(incomeIey)) continue;
					
					String [] keyArray = incomeIey.split("\\*");
					if(keyArray.length != 2) continue;
					
					Pattern p = Pattern.compile("^\\S*" + keyArray[0] + "(\\d*(,\\d{3})*\\.?\\d{0,3}(,\\d{1,3})*)" + keyArray[1] + "\\S*$");
					Matcher m = p.matcher(nhsms.getBody());
					if (m.matches()) {
						String number = m.group(1).trim().replace(",", "");
						RecordMoney recordMoney = new RecordMoney();
						recordMoney.rmid = date++;
						recordMoney.actionType = RecordMoney.ACTION_TYPE_INCOME;
						recordMoney.createTime = nhsms.getDate();
						recordMoney.moneyNum = Float.parseFloat(number);
						recordMoney.objectMember = capitalInfo.number;
						recordMoney.project = "银行/个人资金流动记录";
						recordMoney.remarks = nhsms.getBody() + "\r\n事件号码：" + nhsms.getAddress();
						addRecordMoneyList.add(recordMoney);
					}
				}
			} catch (Exception e) {
				FileUtil.addLog("", RecordMoneyMgr.class, "RecordMoneyMgr", e);
			}
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			FileUtil.addLog("RecordMoneyMgr::AddCapitalDbTask finish addRecordMoneyListSize=" + addRecordMoneyList.size(), RecordMoneyMgr.class, "RecordMoneyMgr", null);
			if(result != null && result){
				if(addRecordMoneyList.size() > 0){
					recordMoneyList.addAll(addRecordMoneyList);
					jisuan();
					new InsertRecordMoneyDbTask(addRecordMoneyList).execute();
					if(onRecordListener != null) onRecordListener.onDataChanged();
				}
			}
			addRecordMoneyList.clear();
			addRecordMoneyList = null;
		}
	}
	
	class InsertCapitalDbTask extends AsyncTask<String, Object, Boolean>{
		
		List<RecordMoney> addRecordMoneyList = new ArrayList<RecordMoney>();
		CapitalInfo capitalInfo = null;
		NhsmsSession nhsmsSession = null;
		boolean matchingOldSms = false;
		
		public InsertCapitalDbTask(CapitalInfo capitalInfo, boolean matchingOldSms){
			this.capitalInfo = capitalInfo;
			this.matchingOldSms = matchingOldSms;
		}
		
		@Override
		protected void onPreExecute() {
			if(matchingOldSms)
				nhsmsSession = (NhsmsSession) ObjectUtil.copySerializableObj(application.getNhSmsMgr().getSessionByAddress(capitalInfo.number));
		}
		
		@Override
		protected Boolean doInBackground(String... params) {
			try {
				recordMoneyDao.insertOrUpdateCapitalInfoEntity(capitalInfo);
				if(nhsmsSession != null){
					List<Nhsms> nhsmsList = nhsmsSession.getNhsms();
					String expenditureKeys = capitalInfo.expenditureKeys;
					String incomeKeys = capitalInfo.incomeIeys;
					
					String[] expenditureKeyArray = null;
					String[] incomeIeyArray = null;
					if(!TextUtils.isEmpty(expenditureKeys))
						expenditureKeyArray = expenditureKeys.split(";");
					if(!TextUtils.isEmpty(incomeKeys))
						incomeIeyArray = incomeKeys.split(";");
					
					long date = new Date().getTime();
					for(Nhsms nhsms : nhsmsList){
						if(expenditureKeyArray != null)
						for(String expenditureKey : expenditureKeyArray){
							if(TextUtils.isEmpty(expenditureKey)) continue;
							
							String [] keyArray = expenditureKey.split("\\*");
							if(keyArray.length != 2) continue;
							
							Pattern p = Pattern.compile("^\\S*" + keyArray[0] + "(\\d*(,\\d{3})*\\.?\\d{0,3}(,\\d{1,3})*)" + keyArray[1] + "\\S*$");
							Matcher m = p.matcher(nhsms.getBody());
							if (m.matches()) {
								String number = m.group(1).trim().replace(",", "");
								RecordMoney recordMoney = new RecordMoney();
								recordMoney.rmid = date++;
								recordMoney.actionType = RecordMoney.ACTION_TYPE_EXPENDITURE;
								recordMoney.createTime = nhsms.getDate();
								recordMoney.moneyNum = Float.parseFloat(number);
								recordMoney.objectMember = capitalInfo.number;
								recordMoney.project = "银行/个人资金流动记录";
								recordMoney.remarks = nhsms.getBody() + "\r\n事件号码：" + nhsms.getAddress();
								addRecordMoneyList.add(recordMoney);
							}
						}
						
						if(incomeIeyArray != null)
						for(String incomeIey : incomeIeyArray){
							if(TextUtils.isEmpty(incomeIey)) continue;
							
							String [] keyArray = incomeIey.split("\\*");
							if(keyArray.length != 2) continue;
							
							Pattern p = Pattern.compile("^\\S*" + keyArray[0] + "(\\d*(,\\d{3})*\\.?\\d{0,3}(,\\d{1,3})*)" + keyArray[1] + "\\S*$");
							Matcher m = p.matcher(nhsms.getBody());
							if (m.matches()) {
								String number = m.group(1).trim().replace(",", "");
								RecordMoney recordMoney = new RecordMoney();
								recordMoney.rmid = date++;
								recordMoney.actionType = RecordMoney.ACTION_TYPE_INCOME;
								recordMoney.createTime = nhsms.getDate();
								recordMoney.moneyNum = Float.parseFloat(number);
								recordMoney.objectMember = capitalInfo.number;
								recordMoney.project = "银行/个人资金流动记录";
								recordMoney.remarks = nhsms.getBody() + "\r\n事件号码：" + nhsms.getAddress();
								addRecordMoneyList.add(recordMoney);
							}
						}
					}
				}
			} catch (Exception e) {
				FileUtil.addLog("", RecordMoneyMgr.class, "RecordMoneyMgr", e);
			}
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			FileUtil.addLog("RecordMoneyMgr::InsertCapitalDbTask finish addRecordMoneyListSize=" + addRecordMoneyList.size(), RecordMoneyMgr.class, "RecordMoneyMgr", null);
			if(result != null && result){
				capitalInfoList.add(capitalInfo);
				if(capitalListener != null) capitalListener.onDataChanged();
				
				if(addRecordMoneyList.size() > 0){
					recordMoneyList.addAll(addRecordMoneyList);
					jisuan();
					new InsertRecordMoneyDbTask(addRecordMoneyList).execute();
					if(onRecordListener != null) onRecordListener.onDataChanged();
				}
			}
			addRecordMoneyList.clear();
			addRecordMoneyList = null;
		}
	}
	
	class DeleteCapitalDbTask extends AsyncTask<String, Object, Boolean>{
		
		CapitalInfo capitalInfo = null;
		boolean matchingOldSms = false;
		
		public DeleteCapitalDbTask(CapitalInfo capitalInfo, boolean matchingOldSms){
			this.capitalInfo = capitalInfo;
			this.matchingOldSms = matchingOldSms;
		}
		
		@Override
		protected void onPreExecute() {
			
		}
		
		@Override
		protected Boolean doInBackground(String... params) {
			recordMoneyDao.deleteCapitalEntity(capitalInfo);
			if(matchingOldSms){
				List<RecordMoney> moneyList = recordMoneyDao.queryRecordMoneyList(capitalInfo.number);
				if(moneyList != null && moneyList.size() > 0){
					recordMoneyDao.deleteRecordMoney(moneyList);
				}
				moneyList.clear();
				moneyList = null;
			}
			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			FileUtil.addLog("RecordMoneyMgr::DeleteCapitalDbTask finish", RecordMoneyMgr.class, "RecordMoneyMgr", null);
			if(result != null && result){
				Toast.makeText(application, R.string.record_del_success, Toast.LENGTH_SHORT).show();
				capitalInfoList.remove(capitalInfo);
				if(capitalListener != null) capitalListener.onDataChanged();
				new InitRecordMoneyDbTask().execute();
			}
		}
	}
	
}
